//
//  NearbyViewController.m
//  Finance
//
//  Created by cheng xiang on 13-4-2.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "NearbyViewController.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
#import "NearbyMotionViewController.h"
#import "NearbyMotionView.h"
#import "NearbyTableViewController.h"

#define MINIMUM_ZOOM_ARC 0.014 //approximately 1 miles (1 degree of arc ~= 69 miles)
#define ANNOTATION_REGION_PAD_FACTOR 1.15
#define MAX_DEGREES_ARC 360

@interface NearbyViewController ()
- (NSDictionary *) exchangeArrayByBank:(NSArray *)array;
@end

@implementation NearbyViewController
@synthesize mapView = _mapView, annotations = _annotations;
@synthesize locationManager = _locationManager, locationDic = _locationDic;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (BOOL)canResignFirstResponder
{
    return YES;
}

-(void)viewWillDisappear:(BOOL)animated {
    
    //[self resignFirstResponder];
    
    [self setHidesBottomBarWhenPushed:NO];//隐藏uitabbar需要这样调用
    [super viewWillDisappear:animated];
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([self.navigationController.navigationBar respondsToSelector:@selector( setBackgroundImage:forBarMetrics:)]){
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"toolbar.jpg"] forBarMetrics:UIBarMetricsDefault];
    }
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"摇一摇" style:UIBarButtonItemStyleBordered target:self action:@selector(goMotion:)];
////     UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"dfgdf.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(goMotion:)];
//   // [leftItem setTitle:@"摇一摇"];
//    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    
//    [self.navigationItem setLeftBarButtonItem:leftItem];

    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    _mapView.delegate = self;
    _mapView.mapType = MKMapTypeStandard;
    _mapView.showsUserLocation = YES;
    [self.view addSubview:_mapView];
	
    [self getCurrentLocation];
}

- (void)viewDidAppear:(BOOL)animated
{    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UITabBarController *aController = (UITabBarController *)delegate.window.rootViewController;
    [delegate showTabBar:aController];
    [super viewDidAppear:animated];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self setHidesBottomBarWhenPushed:NO];
    [super viewWillAppear:animated];
}

- (void)goMotion:(id)sender
{
    [self setHidesBottomBarWhenPushed:YES];//想隐藏uitabbar必调
    NearbyMotionViewController *aController = [[NearbyMotionViewController alloc] init];
    [self.navigationController pushViewController:aController animated:YES];
}

- (void)setRegoinInMap
{
    //定位当前位置 add by chengxiang
    CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(((NSString *)_locationDic[LATITUDE]).doubleValue,((NSString *)_locationDic[LONGITUDE]).doubleValue);

    float zoomLevel = 0.02;
    MKCoordinateRegion region = MKCoordinateRegionMake(coords, MKCoordinateSpanMake(zoomLevel, zoomLevel));
    region.center=[[_locationManager location] coordinate];
    [_mapView setRegion:[_mapView regionThatFits:region] animated:YES];
    
}

- (void)requestCallBack:(NSDictionary *)rdic
{
    NSObject *body = rdic[@"body"];
    NSArray *array = nil;
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"products"] != nil)
    {
        array = [(NSDictionary *)body objectForKey:@"products"];
    }
    NSDictionary *resultDic = [self exchangeArrayByBank:array];
    NSLog(@"%@",resultDic);
    NSMutableArray *annotations = [[NSMutableArray alloc] init];
    
    for (int i = 0; i < [resultDic.allKeys count]; i++) {
        NSString *key = [resultDic.allKeys objectAtIndex:i];
        NSObject *obj = [resultDic objectForKey:key];
        if ([obj isKindOfClass:[NSArray class]] && [(NSArray *)obj count] > 0) {
            NSDictionary *dic = [(NSArray *)obj objectAtIndex:0];
            FinanceAnnotation *annotation1 = [FinanceAnnotation annotationForFinance:[NSDictionary dictionaryWithObjects:@[key,[dic objectForKey:@"latitude"],[dic objectForKey:@"longitude"],[dic objectForKey:@"prodId"]] forKeys:@[ANNOTATION_TITLE,LATITUDE,LONGITUDE,@"prodId"]] withProArray:(NSArray *)obj];
            
            [annotations addObject:annotation1];
        }
    }
    self.annotations = annotations;
}

- (void)getCurrentLocation
{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager startUpdatingLocation];
    }else{
        [_locationManager startUpdatingLocation];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [_locationManager stopUpdatingLocation];
    if (_locationDic == nil) {
        _locationDic = [[NSMutableDictionary alloc] init];
    }
    NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
    NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
    _locationDic[LATITUDE] = strLat;
    _locationDic[LONGITUDE] = strLng;
    NSLog(@"Lat: %@  Lng: %@", strLat, strLng);
    [self setRegoinInMap];
    [self packageRequest];
    
}

- (void)packageRequest
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W115"];
    NSDictionary *body = [self PackageBody:_locationDic[LONGITUDE] lat:_locationDic[LATITUDE]];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    //发送报文
    [self getTableData: requestJson];
}

//每次组报文需要实现类似组body的方法
- (NSDictionary *)PackageBody:(NSString *)longitude lat:(NSString *)latitude
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"longitude"] = longitude;
    dic[@"latitude"] = latitude;
    return dic;
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryProdByGps"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"locError:%@", error);
    
}

- (NSDictionary *) exchangeArrayByBank:(NSArray *)array
{
    NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
    for(NSDictionary *dic in array)
    {
        NSString *bankname = [dic objectForKey:@"bankName"];
        if ([[result allKeys] containsObject:bankname]) {
            NSMutableArray *dicArray = (NSMutableArray *)[result objectForKey:bankname];
            [dicArray addObject:dic];
        }else{
            NSMutableArray *dicArray = [[NSMutableArray alloc] init];
            [dicArray addObject:dic];
            [result setObject:dicArray forKey:bankname];
        }
    }
    return result;
}

//刷新标注 add by chengxiang
- (void)updateMapView
{
    if (self.mapView.annotations) [self.mapView removeAnnotations:self.mapView.annotations];
    if (self.annotations)
    {
        [self.mapView addAnnotations:self.annotations];
        [self zoomMapViewToFitAnnotations:self.mapView animated:YES];  
    }
}

- (void)zoomMapViewToFitAnnotations:(MKMapView *)mapView animated:(BOOL)animated
{
    NSArray *annotations = mapView.annotations;
    int count = [mapView.annotations count];
    if ( count == 0) { return; } //bail if no annotations
    
    //convert NSArray of id <MKAnnotation> into an MKCoordinateRegion that can be used to set the map size
    //can't use NSArray with MKMapPoint because MKMapPoint is not an id
    MKMapPoint points[count]; //C array of MKMapPoint struct
    for( int i=0; i<count; i++ ) //load points C array by converting coordinates to points
    {
        CLLocationCoordinate2D coordinate = [(id <MKAnnotation>)[annotations objectAtIndex:i] coordinate];
        points[i] = MKMapPointForCoordinate(coordinate);
    }
    //create MKMapRect from array of MKMapPoint
    MKMapRect mapRect = [[MKPolygon polygonWithPoints:points count:count] boundingMapRect];
    //convert MKCoordinateRegion from MKMapRect
    MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
    
    //add padding so pins aren't scrunched on the edges
    region.span.latitudeDelta  *= ANNOTATION_REGION_PAD_FACTOR;
    region.span.longitudeDelta *= ANNOTATION_REGION_PAD_FACTOR;
    //but padding can't be bigger than the world
    if( region.span.latitudeDelta > MAX_DEGREES_ARC ) { region.span.latitudeDelta  = MAX_DEGREES_ARC; }
    if( region.span.longitudeDelta > MAX_DEGREES_ARC ){ region.span.longitudeDelta = MAX_DEGREES_ARC; }
    
    //and don't zoom in stupid-close on small samples
    if( region.span.latitudeDelta  < MINIMUM_ZOOM_ARC ) { region.span.latitudeDelta  = MINIMUM_ZOOM_ARC; }
    if( region.span.longitudeDelta < MINIMUM_ZOOM_ARC ) { region.span.longitudeDelta = MINIMUM_ZOOM_ARC; }
    //and if there is a sample of 1 we want the max zoom-in instead of max zoom-out
    if( count == 1 )
    {
        region.span.latitudeDelta = MINIMUM_ZOOM_ARC;
        region.span.longitudeDelta = MINIMUM_ZOOM_ARC;
    }
    [mapView setRegion:region animated:animated];
}

- (void)setMapView:(MKMapView *)mapView
{
    _mapView = mapView;
    [self updateMapView];
}

- (void)setAnnotations:(NSArray *)annotations
{
    _annotations = annotations;
    [self updateMapView];
}

//MKMAPVIEW's delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    //当前位置的小点点忽略掉
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    MKAnnotationView *aView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"MapVC"];
    if (!aView) {
        aView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"MapVC"];
        aView.canShowCallout = YES;
        aView.leftCalloutAccessoryView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
        //左侧我不管了先，右侧得有个进入详情页面的东东啊。。。蛋疼
        aView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    }
    
    aView.annotation = annotation;
    [(UIImageView *)aView.leftCalloutAccessoryView setImage:nil];
    
    return aView;
}

//响应点击详情页面
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    [self setHidesBottomBarWhenPushed:YES];
    NSLog(@"callout accessory tapped for annotation %@", [view.annotation title]);
    NSArray *array = [(FinanceAnnotation *)view.annotation proArray];
    NearbyTableViewController *aController = [[NearbyTableViewController alloc] init];
    aController.array = array;
    [self.navigationController pushViewController:aController animated:YES];
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)aView
{
    
}

@end
